/**
 *@描述：创建知识-参考引用添加页面
 *@作者：殷健
 *@创建时间：2022/7/7
 *@最后修改时间：2022/7/7
 */

import {useEffect, useState} from 'react';
import {Button, Typography, List, Popconfirm, Tag, Modal, Space, Radio, message} from 'antd';
import ProForm, { ProFormText, ProFormDatePicker } from '@ant-design/pro-form';

import {
    PlusOutlined,
    LinkOutlined,
    EditOutlined,
    DeleteOutlined,
    GlobalOutlined,
} from '@ant-design/icons';

import {getReferenceTypesData, ReferenceDelRequest, ReferenceListRequest, ReferenceSaveRequest} from '../../service';
import styles from './style.less';
import {useUpdateEffect} from "ahooks";
const { Text } = Typography;

//
const Quote = (
    {
        title,
        knowledgeId,
        curSection,
        setCurSection,
    }:{
        title:string;
        knowledgeId?:string;
        curSection:AircasKB.Knowledge.SectionItem;
        setCurSection?: (val: AircasKB.Knowledge.SectionItem) => void;
    }
) => {
    // const [curSectionData, setCurSectionData] = useState<AircasKB.Knowledge.SectionItem>(curSection);
    const [showAddQuoteModal, setShowAddQuoteModal] = useState<boolean>(false);
    const [ loading,setLoading ] = useState(false);
    const [ data,setData ] = useState<AircasKB.Knowledge.ReferenceListResponse[]>([{
        id:"",
        referenceType:"",
        title:"",
        source:"",
    }]);

    useUpdateEffect(() => {
        setCurSection?.(curSection);
    }, [curSection]);
    useEffect(()=>{
        if(!knowledgeId){
            message.warn("请首先进入基本信息页面，填写基本信息！");
            setCurSection?.({
                id: 'basic',
                title: '基本信息'
            })
        }
        else{
            getReferenceList();
        }
    },[])

    const getReferenceList = async () => {
        setLoading(true);
        const res:AircasKB.ResponseType<AircasKB.Knowledge.ReferenceListResponse[]> = await ReferenceListRequest({
            knowledgeId:knowledgeId
        })
        if(res.code == 200){
            setData(res.data);
        }
        setLoading(false);
    }

    const doDelListItem = async (obj:any) => {
        const res:AircasKB.ResponseType<AircasKB.Knowledge.ReferenceDelResponse> = await ReferenceDelRequest({
            referenceId:obj.id
        });
        if(res.code == 200){
            getReferenceList();
        }
    }

    return (
        <div className={styles.wrapper}>
            <div className={styles.subTitle} style={{ marginBottom: 0 }}>
                <Text>参考引用</Text>
            </div>
            <div className={styles.formControl}>
                <QuoteList knowledgeId={knowledgeId} loading={loading} data={data} onDel={doDelListItem}/>
                <Button
                    type="dashed"
                    size="large"
                    block
                    icon={<PlusOutlined />}
                    onClick={() => setShowAddQuoteModal(true)}
                >
                    添加引用
                </Button>
            </div>
            {showAddQuoteModal && (
                <AddQuoteModal
                    knowledgeId = {knowledgeId}
                    show={showAddQuoteModal}
                    onCancel={() => setShowAddQuoteModal(false)}
                    onSuccess1={getReferenceList}
                    setShowAddQuoteModal={setShowAddQuoteModal}
                ></AddQuoteModal>
            )}
        </div>
    );
};

const QuoteList = (
    {
        mode = 'edit',
        knowledgeId,
        loading,
        data,
        onDel,
    }:{
        mode?: 'view' | 'edit' ;
        knowledgeId?:string;
        loading?:boolean;
        data?:AircasKB.Knowledge.ReferenceListResponse[];
        onDel?:(obj: any)=>void;
    }) => {

    const doRemoveQuote = async (obj: any) => {
        //TODO 删除
        // @ts-ignore
        onDel(obj);
    };

    return (
        <List
            bordered={false}
            loading={loading}
            itemLayout="horizontal"
            dataSource={data}
            renderItem={(item:AircasKB.Knowledge.ReferenceListResponse) => (
                <List.Item
                    actions={
                        mode === 'edit'
                            ? [
                                  <Button
                                      size="small"
                                      type="link"
                                      icon={<EditOutlined />}
                                  ></Button>,
                                  <Popconfirm
                                      title="确认删除吗？"
                                      okText="确定"
                                      cancelText="取消"
                                      onConfirm={() => doRemoveQuote(item)}
                                  >
                                      <Button
                                          size="small"
                                          type="link"
                                          danger
                                          icon={<DeleteOutlined />}
                                      ></Button>
                                  </Popconfirm>,
                              ]
                            : []
                    }
                >
                    {/*{item?.referenceType === "21" && (*/}
                    {/*    <List.Item.Meta*/}
                    {/*        avatar={<BookOutlined />}*/}
                    {/*        description={*/}
                    {/*            <Space>*/}
                    {/*                <a href={item.source}  target="_blank">{item?.title}</a>.*/}
                    {/*                <span>{item.source}</span>.*/}
                    {/*                <em>[引用日期：{item?.refDate}]</em>*/}
                    {/*            </Space>*/}
                    {/*        }*/}
                    {/*    />*/}
                    {/*)}*/}
                    {/*{item?.referenceType === "20" && (*/}
                    {/*   */}
                    {/*)}*/}
                    <List.Item.Meta
                        avatar={<GlobalOutlined />}
                        description={
                            <Space>
                                <Button type="link" size="small">{item?.title}</Button>.
                                {/*<a href={item.source} target="_blank">{item?.title}</a>.*/}
                                <span>{item.source}</span>.
                                <em>[引用日期：{item?.refDate}]</em>
                            </Space>
                        }
                    />
                    <Tag>{item?.referenceType === '21' ? '著作资料' : '网络资料'}</Tag>
                </List.Item>
            )}
        />
    );
};

const AddQuote = (
    {
        knowledgeId,
        onSuccess,
        setShowAddQuoteModal,
    }:{
        knowledgeId?:string;
        onSuccess?:()=>void;
        setShowAddQuoteModal?:(val:boolean)=>void;
    }
) => {
    const [curType, setCurType] = useState<string>('');
    const [ referenceTypes,setReferenceTypes ] = useState<AircasKB.Knowledge.ReferenceTypesResponse[]>();
    const doSave = async (values: Record<string, any>) => {
        //TODO 保存
        const requestParams:AircasKB.Knowledge.ReferenceSaveRequestParams = {
            ...values,
            knowledgeId:knowledgeId,
            referenceType:curType
        }
        ReferenceSaveRequest(requestParams).then(res => {
            if(res.code == 200){
                // @ts-ignore
                onSuccess();
                setShowAddQuoteModal?.(false);
                message.success("保存成功！");
            }
            else{
                message.error("保存失败！");
            }
        });

    };

    const getReferenceTypes = async () => {
        try {
            const res:AircasKB.ResponseType<AircasKB.Knowledge.ReferenceTypesResponse[]> = await getReferenceTypesData();
            if(res.code == 200){
                setReferenceTypes(res.data);
                setCurType(res.data[0].id??"");
            }
            else{
                setReferenceTypes([]);
            }
        }
        catch (err:any){
            setReferenceTypes([]);
        }
    }
    useEffect(()=>{
        getReferenceTypes();
    },[])

    return (
        <div className={styles.quoteFormWrapper}>
            <div className={styles.header}>
                <Radio.Group
                    defaultValue="20"
                    buttonStyle="solid"
                    onChange={(e) => setCurType(e.target.value)}
                >
                    {
                        referenceTypes?.map((item)=>{
                            return(
                                <Radio.Button value={item.id}>{item.label}</Radio.Button>
                            )
                        })
                    }
                    {/*<Radio.Button value="reference_type_network_information">网络资料</Radio.Button>*/}
                    {/*<Radio.Button value="reference_type_book">著作资料</Radio.Button>*/}
                </Radio.Group>
            </div>
            <div className={styles.content}>
                <ProForm
                    layout="horizontal"
                    className={styles.form}
                    labelCol={{
                        style: {
                            width: 120,
                        },
                    }}
                    onFinish={doSave}
                    initialValues={{}}
                    submitter={{
                        resetButtonProps: {
                            style: {
                                marginLeft: 120,
                            },
                        },
                    }}
                >
                    {curType === '20' && (
                        <>
                            <ProFormText
                                name={'website'}
                                label="网址"
                                required
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入网址',
                                    },
                                ]}
                            ></ProFormText>
                            <ProFormText
                                name={'title'}
                                label="标题"
                                required
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入标题',
                                    },
                                ]}
                            ></ProFormText>
                            <ProFormText
                                name={'webName'}
                                label="网站/平台名称"
                                required
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入标题',
                                    },
                                ]}
                            ></ProFormText>
                            <ProFormDatePicker
                                name={'publishDate'}
                                label="发布日期"
                            ></ProFormDatePicker>
                        </>
                    )}
                    {curType === '21' && (
                        <>
                            <ProFormText
                                name={'workTitle'}
                                label="著作名称"
                                required
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入著作名称',
                                    },
                                ]}
                            ></ProFormText>
                            <ProFormText
                                name={'author'}
                                label="作者"
                                required
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入作者',
                                    },
                                ]}
                            ></ProFormText>
                            <ProFormText
                                name={'publisherName'}
                                label="出版/刊物名称"
                                required
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入标题',
                                    },
                                ]}
                            ></ProFormText>
                            <ProFormDatePicker
                                name={'publishDate'}
                                label="出版日期/刊次"
                            ></ProFormDatePicker>
                            <ProFormText name="referencePage" label="引文页码"></ProFormText>
                        </>
                    )}
                </ProForm>
            </div>
        </div>
    );
};

const AddQuoteModal = (
    {
        show,
        onCancel,
        knowledgeId,
        onSuccess1,
        setShowAddQuoteModal,
    }: {
        show: boolean;
        onCancel?: () => void;
        knowledgeId?:string;
        onSuccess1?:()=>void;
        setShowAddQuoteModal?:(val:boolean)=>void;
    }) => {
    return (
        <Modal
            title={
                <Space>
                    <LinkOutlined />
                    新增参考引用
                </Space>
            }
            visible={show}
            width={600}
            centered
            destroyOnClose={true}
            footer={false}
            bodyStyle={{ padding: 20 }}
            onCancel={onCancel}
        >
            <AddQuote knowledgeId={knowledgeId} onSuccess={onSuccess1} setShowAddQuoteModal={setShowAddQuoteModal}/>
        </Modal>
    );
};

export default Quote;
export { QuoteList };
